<?php
declare (strict_types=1);

namespace app\api\controller;

use addons\WeChatMini\facade\WeChatMini;
use app\common\model\OrderTemporary;
use app\common\tool\Result;
use think\Response;

class Order extends Base
{
    public function getTemporary(): Response
    {
        return Result::fastReturn(OrderTemporary::getTemporary($this->user->id));
    }

    public function submit(): Response
    {
        $param = $this->request->post();

        return Result::fastReturn(OrderTemporary::submit($param, $this->user));
    }

    public function replaceAddress(): Response
    {
        $param = $this->request->post();

        return Result::fastReturn(OrderTemporary::replaceAddress($param, $this->user));
    }

    public function payment($id): Response
    {
        return Result::fastReturn(OrderTemporary::getPayment($id, $this->user));
    }

    public function confirmPayment(): Response
    {
        $param = $this->request->post();

        return Result::fastReturn(OrderTemporary::payment($param, $this->user));
    }

    public function index(): Response
    {
        $param = $this->request->get();
        $map['uid'] = $this->user->id;
        if (!empty($param['status'])) {
            $map['status'] = $param['status'];
        }
        $result = OrderTemporary::getPageList($map, 'id,sn,num,total_amount,freight,real_amount,status,pay_way,waybill_token,create_time',
            $this->getPage(), $this->getLimit(), false, ['productsField'], [], [], [], [], '', ['status_name']);
        foreach ($result['data'] as &$item) {
            $item->pay_method = $item->getData('pay_way');
            $item->mch_id = config('pay')['wechat']['mch_id'];
        }

        return Result::fastReturn($result);
    }

    public function info($id): Response
    {
        $info = OrderTemporary::with(['productsField', 'p', 'c', 'd', 'express'])
            ->withoutField('address_id,update_time,delete_time')
            ->where(['id' => $id, 'uid' => $this->user->id])->find();
        if (empty($info)) return Result::fail('订单不存在');
        $info->pay_method = $info->getData('pay_way');
        $info->mch_id = config('pay')['wechat']['mch_id'];
        $info->friendlyText = getProductOrderFriendly($info->status);
        if ($info->status == 1) {
            $info->surplus_time = round(($info->expire_time - time()) * 1000);
        } elseif ($info->status == 3) {
            $info->surplus_time = round(($info->auto_receipt_time - time()) * 1000);
        } else {
            $info->surplus_time = 0;
        }
        $p = $info->p ? $info->p->title : '';
        $c = $info->c ? $info->c->title : '';
        $d = $info->d ? $info->d->title : '';
        $info->address = $p . $c . $d;
        $info->expressInfo = $info->express ?: '';
        unset($info->p, $info->c, $info->d, $info->province, $info->city, $info->district, $info->town, $info->express);

        return Result::success('success', $info);
    }

    public function getWaybillToken($id): Response
    {
        $info = OrderTemporary::where(['id' => $id, 'uid' => $this->user->id])
            ->whereIn('status', [3, 4, 5])->find();
        if (empty($info)) return Result::fail('订单不存在');
        if (empty($info->express)) return Result::fail('该订单未发货');
        if (!empty($info->waybill_token)) {
            $token = $info->waybill_token;
        } else {
            $goods = [];
            foreach ($info->productsField as $item) {
                $goods[] = [
                    'goods_name' => $item->title . $item->spec,
                    'goods_img_url' => request()->domain() . '/' . $item->icon
                ];
            }
            $res = WeChatMini::traceWaybill([
                'openid' => $info->openid,
                'receiver_phone' => $info->receiver_tel,
                'delivery_id' => $info->express->code,
                'waybill_id' => $info->express_code,
                'trans_id' => $info->transaction_id,
                'goods_info' => [
                    'detail_list' => $goods
                ]
            ]);
            if ($res['errmsg'] != 'ok') {
                return Result::fail('查询失败');
            }
            $token = $res['waybill_token'];
            $info->waybill_token = $token;
            $info->save();
        }
        $result = [
            'mch_id' => config('pay')['wechat']['mch_id'],
            'token' => $token
        ];

        return Result::success('success', $result);
    }

    public function edit(): Response
    {
        $param = $this->request->post();

        return Result::fastReturn(OrderTemporary::edit($param, $this->user));
    }
}